import { Injectable } from '@angular/core';
import { RestService } from '@abp/ng.core';
import { CreateUpdateShopDto, ShopDto } from './models';
import { Observable } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ShopService {
  apiName = 'Default';

  constructor(private restService: RestService) {}

  getList(params: any = {}): Observable<any> {
    console.log('调用getList API，参数:', params);
    return this.restService.request<any, any>({
      method: 'GET',
      url: '/api/app/shop',
      params
    }).pipe(
      tap(response => console.log('API返回数据:', response)),
      catchError(this.handleError)
    );
  }

  searchByName(nameKeyword: string, params: any = {}): Observable<any> {
    console.log('调用searchByName API，关键字:', nameKeyword);
    return this.restService.request<any, any>({
      method: 'GET',
      url: '/api/app/shop/search-by-name',
      params: {
        nameKeyword,
        skipCount: params['skipCount'] || 0,
        maxResultCount: params['maxResultCount'] || 10,
        sorting: params['sorting'] || ''
      }
    }).pipe(
      tap(response => console.log('搜索商品成功:', response)),
      catchError(this.handleError)
    );
  }

  getById(id: string): Observable<ShopDto> {
    console.log('调用getById API，ID:', id);
    // 确保ID被正确编码
    return this.restService.request<any, ShopDto>({
      method: 'GET',
      url: `/api/app/shop/${encodeURIComponent(id)}`
    }).pipe(
      tap(response => console.log('获取商品详情成功:', response)),
      catchError(this.handleError)
    );
  }

  create(input: CreateUpdateShopDto): Observable<ShopDto> {
    console.log('调用create API，数据:', input);
    return this.restService.request<any, ShopDto>({
      method: 'POST',
      url: '/api/app/shop',
      body: input
    }).pipe(
      tap(response => console.log('创建商品成功:', response)),
      catchError(this.handleError)
    );
  }

  update(id: string, input: CreateUpdateShopDto): Observable<ShopDto> {
    console.log('调用update API，ID:', id, '数据:', input);
    // 确保ID被正确编码
    return this.restService.request<any, ShopDto>({
      method: 'PUT',
      url: `/api/app/shop/${encodeURIComponent(id)}`,
      body: input
    }).pipe(
      tap(response => console.log('更新商品成功:', response)),
      catchError(this.handleError)
    );
  }

  delete(id: string): Observable<void> {
    console.log('调用delete API，ID:', id);
    // 确保ID被正确编码
    return this.restService.request<any, void>({
      method: 'DELETE',
      url: `/api/app/shop/${encodeURIComponent(id)}`
    }).pipe(
      tap(() => console.log('删除商品成功')),
      catchError(this.handleError)
    );
  }

  private handleError = (error: HttpErrorResponse) => {
    console.error('API错误:', error);
    let errorMessage = '发生未知错误';
    
    if (error.error instanceof ErrorEvent) {
      // 客户端错误
      errorMessage = `客户端错误: ${error.error.message}`;
    } else {
      // 服务器错误
      errorMessage = `服务器错误: ${error.status}, 消息: ${error.message}`;
      
      // 尝试获取更详细的错误信息
      if (error.error && error.error.error) {
        if (error.error.error.message) {
          errorMessage += `, 详情: ${error.error.error.message}`;
        }
        if (error.error.error.details) {
          errorMessage += `, 详细信息: ${error.error.error.details}`;
        }
      }
    }
    
    console.error(errorMessage);
    throw error;
  }
} 